﻿define(["angularAMD", "moment"], function (angularAMD, moment) {
    angularAMD.service('LineChangeService', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog',
        function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog) {
            this.init = function (machine, feedback) {
                var nowdatetime = $filter('date')(new Date(), 'yyyy/MM/dd HH:mm:ss');
                var dialogOpen = function (status_item, remark_name = '') {
                    $mdDialog.dialog(
                        'module/moduleB/program/B02/B0201/LineChange.html',
                        function (dialog) {
                            return {
                                css_url: 'module/moduleB/program/B02/B0201/LineChange.css',
                                machine: machine,
                                status_item: status_item,
                                remark: '',
                                remark_name: remark_name,
                                maintain_order_list: [],
                                handle_user_no: config.cache.account,
                                flag: true,
                                plan_work: {
                                    date: nowdatetime.split(' ')[0],
                                    time: nowdatetime.split(' ')[1]
                                },
                                beforeShown: function () {
                                    if (machine.machine_status == '3') {
                                        maintainOrderInfoGet(function (data) {
                                            dialog.maintain_order_list = data.maintain_order_list || [];
                                        });
                                    }
                                },
                                showMaintainOrder: function () {
                                    return (dialog.machine.machine_status == '3' && dialog.maintain_order_list.length > 0);
                                },
                                changeStatus: function (status) {
                                    // 202400322 add by Alan for M#160269: 補上#113735
                                    dialog.flag = false;
                                    dialog.machine_status = status.code;
                                    dialog.have_reason = status.have_reason;
                                    dialog.require_reason = status.require_reason;
                                    dialog.remark = '';
                                    dialog.remark_name = '';
                                    // 20240326 modify by wenwei for M#160368: [Oracle][H5][设备稼动]生产线工作平台保养暂停设置原因都没有自动弹出
                                    if (status.code == '5' || status.code == '3' ||status.code == '2' || status.code =='7' || status.code =='6') {
                                        dialog.changeRemark();
                                    }
                                },
                                changeRemark: function () {
                                    var value_types = { '2': 'DOWN', '6': 'REPAIR', '3': 'MAINTAIN', '7': 'SETUP', '5': 'SUSPEND' };
                                    // 202400322 add by Alan for M#160269: 補上#113735
                                    var value = value_types[dialog.machine_status] || value_types[dialog.machine.machine_status];

                                    if (value == undefined)
                                        value = 'DOWN';
                                    //20190705 modify by Dustdusk for M#59591:
                                    var open_select = function (items) {
                                        $rootScope.showSelect({
                                            label: function (item) {
                                                return item.page_name + '(' + item.page_no + ')';
                                            },
                                            code: 'page_no',
                                            selectCode: dialog.remark,
                                            list: items,
                                            confirm: function (item, radio_dialog) {
                                                radio_dialog.hide();
                                                dialog.remark = item.page_no;
                                                dialog.remark_name = item.page_name;
                                            }
                                        });
                                    }
                                    // 202400322 add by Alan for M#160269: 補上#139989
                                    equipment_reason_get(value, machine.machine_no, function (items) {
                                        if (items.length == 0)
                                            equipment_reason_get(value, undefined, open_select);
                                        else
                                            open_select(items);
                                    });
                                },
                                openMaintainOrder: function () {
                                    $mdDialog.serviceDialog('B0232Service', {
                                        machine_no: dialog.machine.machine_no,
                                        maintain_order_list: dialog.maintain_order_list,
                                        callback: function () {
                                            dialog.beforeShown();
                                        }
                                    });
                                },
                                back: function () {
                                    dialog.hide();
                                },
                                //20170516 modify by Dustdusk for 修正故障原因未輸入的卡控
                                confirm: function () {
                                    if (!dialog.machine.machine_no) {
                                        $rootScope.showAlert($filter('translate')('B0211.showAlert.column1'));
                                    } else if (dialog.require_reason == '1' && dialog.remark == '') {
                                        $rootScope.showAlert($filter('translate')('B0211.showAlert.column3'));
                                    } else {
                                        // 20200623 modify by linzh for M#71452 - 使用日期套件更換日期，會強制轉為 GMT 時間格式，所以需要再轉換一次。
                                        var work_time = $filter('date')(dialog.plan_work.date, 'yyyy/MM/dd') + " " + dialog.plan_work.time;
                                        var content = {
                                            machine_no: dialog.machine.machine_no,
                                            report_datetime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                                            machine_status: dialog.machine_status || dialog.machine.status,
                                            remark: dialog.remark,
                                            handle_user_no: dialog.handle_user_no,
                                            plan_start_time: dialog.machine_status == '0' || dialog.machine_status == '1' ? '' : work_time,
                                            actual_end_time: dialog.machine_status == '0' || dialog.machine_status == '1' ? work_time : '',
                                            remarks: dialog.remarks
                                        };
                                        changeMachineStatusProcess(content, dialog);
                                    }
                                },
                                //20200611 add by linzh for M#71452
                                loadHandleUserNoList: function () {
                                    //20200623 modify by linzh for M#71452 取得用户资料
                                    $MMWService.showQueryListPNIG({
                                        page_mode: 'user_no_info_get',
                                        pageRecord: 50,
                                        condition: [
                                            { name: $filter('translate')('common.queryList.employee_c'), column_name: 'UserNo', query_mode: '2', value: dialog.handle_user_no }
                                        ],
                                        header: [
                                            { label: $filter('translate')('common.queryList.employee_c'), code: 'user_no' },
                                            { label: $filter('translate')('common.queryList.employee_n'), code: 'user_name' }
                                        ],
                                        setCondition: function (conditions) {
                                            conditions.push(
                                                { column_name: 'IssueState', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                                            );
                                            return conditions;
                                        },
                                        selectCode: dialog.handle_user_no || '',
                                        confirm: function (selectItem, dialog2) {
                                            dialog.handle_user_no = selectItem.user_no;
                                            dialog2.hide();
                                        }
                                    });
                                }
                            };
                        }
                    );
                };

                // 保養單資訊取得
                function maintainOrderInfoGet(callback) {
                    var content = {
                        machine_no: machine.machine_no
                    };
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_EQP.maintain_order_info_get',
                        content: content,
                        success: function (data) {
                            if (callback)
                                callback(data);
                        }
                    });
                }

                function changeMachineStatusProcess(content, dialog) {
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_EQP.edit_machine_state_process',
                        content: content,
                        success: function (data) {
                            $rootScope.showToast($filter('translate')('B0211.showAlert.column4'));
                            dialog.hide();
                            if (feedback)
                                feedback(content);
                        }
                    });
                }

                //20190705 modify by Dustdusk for M#59591:
                function equipment_reason_get(type, machine_no, callback) {
                    var query_condition_info = [
                        { column_name: 'REASONTYPE', query_mode: '0', merge_condition_model: 'AND', value: '6' },
                        { column_name: 'REASONSUBTYPE', query_mode: '0', merge_condition_model: 'AND', value: type },
                        { column_name: 'a.Equipment', query_mode: '0', merge_condition_model: 'AND', value: machine_no }
                    ];
                    // if(machine_no!= undefined)
                    // query_condition_info.push({column_name:'a.Equipment', query_mode:'0', merge_condition_model:'AND', value: machine_no });
                    $MMWService.pageNumberInfoGet({
                        page_mode: 'equipment_reason_get',
                        query_condition_info: query_condition_info
                    }, function (items) {
                        if (typeof (callback) == 'function')
                            callback(items);
                    });
                }

                (function machineStatusGet() {
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_EQP.machine_status_info_get',
                        content: { machine_no: machine.machine_no },
                        success: function (data) {
                            if (data.machine_status_get_detail.length > 0) {
                                machine.machine_status = data.machine_status_get_detail[0].status;
                                machine.machine_runtime = data.machine_status_get_detail[0].machine_runtime;
                                // 202400322 add by Alan for M#160269: 補上#113735
                                var value_types = { '2': 'DOWN', '6': 'REPAIR', '3': 'MAINTAIN', '7': 'SETUP', '5': 'SUSPEND' };
                                var value = value_types[machine.machine_status];
                                equipment_reason_get(value, data.machine_status_get_detail[0].machine_no, function (items) {
                                    let remark = items.find(item => item.page_no == data.machine_status_get_detail[0].remark) || {};
                                    dialogOpen(data.machine_status_get_detail[0].allow_status_detail, remark.page_name);
                                });
                            }
                        }
                    });
                })();
            };
        }]);
});